﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using FoursquareNET.Schema;

namespace FoursquareNET
{
    public static class Common
    {
        public enum HttpRequestMethod
        {
            POST,
            GET
        }

        internal static string HTTPPost(string url, List<Parameter> parameters, Credential credential, HttpRequestMethod httpRequestMethod)
        {
            url = GenerateUrl(url, parameters);

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);

            if (!string.IsNullOrEmpty(credential.Phone_or_Email) && !string.IsNullOrEmpty(credential.Password))
            {
                string authenticationHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", credential.Phone_or_Email, credential.Password)));
                httpRequest.Headers["Authorization"] = "Basic " + authenticationHeader;
            }

            httpRequest.Method = httpRequestMethod.ToString();
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        string result = reader.ReadToEnd();
                        return result;
                    }
                }
            }
            catch (System.Net.WebException ex)
            {
                string result = new StreamReader(((HttpWebResponse)ex.Response).GetResponseStream(), Encoding.UTF8).ReadToEnd();
                ErrorObj error = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Schema.ErrorObj>(result);

                if (!string.IsNullOrEmpty(error.Error))
                    throw new Exception.WebException(error.Error);

                else if (!string.IsNullOrEmpty(error.RateLimited))
                    throw new Exception.RateLimitedException(error.RateLimited);

                else if (!string.IsNullOrEmpty(error.Unauthorized))
                    throw new Exception.UnauthorizedException(error.Unauthorized);

                else
                    throw ex;
            }
        }

        private static string GenerateUrl(string URL, List<Parameter> Parameters)
        {
            StringBuilder url = new StringBuilder(URL);

            url.Append(".json?");

            foreach (var parameter in Parameters)
            {
                if (parameter.Required && string.IsNullOrEmpty(parameter.Value))
                    throw new Exception.RequiredParameterException(parameter.Alias);

                if (!string.IsNullOrEmpty(parameter.Value))
                    url.AppendFormat("{0}={1}&", parameter.Key, parameter.Value);
            }
            url.Remove(url.Length - 1, 1);

            return url.ToString();
        }
    }
}
